package com.example.uniquekey;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class UniqueKeyGenerator {

    @Resource
    private ConnectionFactory connectionFactory;

    /**
     * 存储唯一 ID 生成器 <tableName, GeneralKeyGenerator>
     */
    private static final Map<String, GeneralKeyGenerator> generatorMap = new HashMap<>();
    /**
     * 当表的 ID 是第一次生成时，初使ID = MIN_VALUE，可自行修改
     */
    private static final long MIN_VALUE = 1000000000;

    /**
     * 自定义获取唯一 Key 生成生成器
     *
     * @param keyName keyName
     * @param initVal 最小值
     * @return GeneralKeyGenerator
     */
    public GeneralKeyGenerator getCustomerKeyGenerator(String keyName, long initVal) {
        if (!generatorMap.containsKey(keyName)) {
            synchronized (generatorMap) {
                if (!generatorMap.containsKey(keyName)) {
                    GeneralKeyGenerator generator = new GeneralKeyGenerator(keyName);
                    generator.setConnectionFactory(connectionFactory);
                    generator.setMinValue(initVal);
                    generatorMap.put(keyName, generator);
                }
            }
        }
        return generatorMap.get(keyName);
    }

    /**
     * 生成 默认ID
     *
     * @param tableName 表名
     * @return long
     */
    public long generate(String tableName) {
        if (!generatorMap.containsKey(tableName)) {
            synchronized (generatorMap) {
                if (!generatorMap.containsKey(tableName)) {
                    GeneralKeyGenerator generator = new GeneralKeyGenerator(tableName);
                    generator.setConnectionFactory(connectionFactory);
                    generator.setMinValue(MIN_VALUE);
                    generatorMap.put(tableName, generator);
                }
            }
        }
        return generatorMap.get(tableName).nextKey();
    }
}
